package tools;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.nio.file.FileVisitor;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import scrapper.AbstractScrapper;
import scrapper.SauceNaoScrapper;

import files.ProcessFile;

public class ArtistSorterWeb {

	public static void main(String[] args) {
		String root = "K:\\(｡･｀ω´･｡)\\2d\\unsorted_backup";
		FileVisitor<Path> fileProcessor = null;
		try {
			fileProcessor = new ProcessFile(root, false);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Map<String, String> cookies = new HashMap<String, String>();
		cookies.put("user", "1648;");
		cookies.put("auth", "e4e217ff7a747fed5aa9274645dc946c6d810238;");

		String name = "";
		int res = 0;
		int cpt = 0;
		AbstractScrapper p1 = null;
		File temp = null, temp2 = null;
		for(File f : ((ProcessFile) fileProcessor).getList()) {
			name = f.getName();
			try {
				p1 = new SauceNaoScrapper("", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0");
				p1.setUrl("http://saucenao.com/search.php?db=999&url=http://home.aidturith.com/private/"+name);
				p1.setLoginCookies(cookies);
				res = p1.connectWithCookies();
				/*while((res = p1.connect()) != 0) {
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.err.println("Page not found for "+name+"!");
					System.out.println(p1.getUrl());
				}*/
				if(res == 0) {
					if(p1.buildPage()) {
						//System.out.println(p1.getAuthor());
						temp = new File("K:\\(｡･｀ω´･｡)\\2d\\unsorted_backup\\"+p1.getAuthor()+", "+p1.getAuthorID()+"\\"+p1.getFile()+"_._"+name);
						temp2 = new File("K:\\(｡･｀ω´･｡)\\2d\\unsorted_backup\\"+p1.getAuthor()+", "+p1.getAuthorID());
						System.out.println(cpt+"\t"+name);
						System.out.println(temp.getAbsolutePath());
						temp2.mkdirs();
						f.renameTo(temp);
					}
					else {
						System.err.println("Low similarity for "+name+"!");
						temp = new File("K:\\(｡･｀ω´･｡)\\2d\\unsorted_backup\\_lowSimilarity\\"+name);
						System.out.println(temp.getAbsolutePath());
						f.renameTo(temp);
					}
				}
				else
					System.err.println("Page not found for "+name+"!");
				
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			cpt++;
		}
		System.out.println(((ProcessFile) fileProcessor).getList().size()+" images browsed!");
	}

}
